package com.czp.infosharingplatformapp.controller;

import com.czp.infosharingplatformapp.dto.CategoryResponse;
import com.czp.infosharingplatformapp.model.Category;
import com.czp.infosharingplatformapp.model.Post;
import com.czp.infosharingplatformapp.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/categories")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    // 获取所有分类
    @GetMapping
    public List<CategoryResponse> getAllCategories() {
        List<Category> categories = categoryService.getAllCategories();
        return categories.stream()
                .map(categoryService::convertToCategoryResponse)
                .collect(Collectors.toList());
    }

    // 获取所有一级分类
    @GetMapping("/top")
    public List<CategoryResponse> getAllTopCategories() {
        List<Category> categories = categoryService.findAllTopCategories();
        return categories.stream()
                .map(categoryService::convertToCategoryResponse)
                .collect(Collectors.toList());
    }

    // 获取某个分类的子分类
    @GetMapping("/{parentId}/subcategories")
    public List<CategoryResponse> getSubCategories(@PathVariable Long parentId) {
        List<Category> categories = categoryService.findSubCategories(parentId);
        return categories.stream()
                .map(categoryService::convertToCategoryResponse)
                .collect(Collectors.toList());
    }

    // 创建分类
    @PostMapping
    public CategoryResponse createCategory(@RequestParam String name, @RequestParam(required = false) Long parentId) {
        return categoryService.convertToCategoryResponse(categoryService.createCategory(name, parentId));
    }

    // 删除分类
    @PreAuthorize("hasRole('ADMIN')")
    @DeleteMapping("/{id}")
    public String deleteCategory(@PathVariable Long id) {
        categoryService.deleteCategory(id);
        return "分类已删除！";
    }

    // 获取所有子分类
    @GetMapping("/subcategories")
    public List<CategoryResponse> getAllSubCategories() {
        List<Category> categories = categoryService.getAllSubCategories();
        return categories.stream()
                .map(categoryService::convertToCategoryResponse)
                .collect(Collectors.toList());
    }
}